package com.myschool.server.web.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.myschool.common.exception.ApplicationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myschool.server.manager.SubjectMasterManager;
import com.myschool.server.model.Json;
import com.myschool.server.model.SubjectMaster;

@Controller
public class SubjectMasterController {

	@Autowired
	SubjectMasterManager subjectMasterManager;

	@RequestMapping("getMasterSubjects.htm")
	public @ResponseBody
	Json<SubjectMaster> retrieveAllSubjects(HttpServletRequest request) {

		Json<SubjectMaster> jsonData = new Json<SubjectMaster>();

		List<SubjectMaster> subjects = subjectMasterManager.retrieveAll();

		jsonData.setPage(1);
		jsonData.setRecord(2);
		jsonData.setTotal(2);
		jsonData.setRowList(subjects);
		return jsonData;
	}

	@RequestMapping("addMasterSubjects.htm")
	public @ResponseBody
	ModelMap addSubjects(HttpServletRequest request, SubjectMaster subjectMaster) {
		ModelMap map = new ModelMap();
		try {

			subjectMaster = this.subjectMasterManager.create(subjectMaster);
			map.addAttribute("message", "Subject added successfully");
			map.addAttribute("entityId", subjectMaster.getEntityId());
		} catch (ApplicationException e) {
			map.addAttribute("message", "Error during subject save.");
		}
		return map;

	}

	@RequestMapping("deleteMasterSubjects.htm")
	public @ResponseBody
	ModelMap deleteSubjects(HttpServletRequest request) {
		ModelMap map = new ModelMap();
		String deleteIds = request.getParameter("deleteIds"); 
		boolean isError = false;
		String[] ids = deleteIds.split(";");
		List<String> delIds=new ArrayList<String>();
		for (String id : ids) {
			try {
				Long entityId = Long.parseLong(id);
				this.subjectMasterManager.delete(entityId);
				delIds.add(id);
			} catch (NumberFormatException numExp) {
				numExp.printStackTrace();
				isError = true;
				// id is not right
			} catch (ApplicationException e) {
				e.printStackTrace();
				isError = true;
				// map.addAttribute("message", "Error during subject delete.");
			}

		}
		if (isError) {
			map.addAttribute("message", "Error during Subjects deletion");
		} else {
			map.addAttribute("message", "Subjects deleted successfully");
		}
      map.addAttribute("deletedItems", delIds);
		return map;

	}

}
